package com.wsj.dao.hibernate;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.wsj.dao.IMagazineClassDao;
import com.wsj.util.page.PageResultSet;
import com.wsj.util.page.PerfectPageResultSet;
import com.wsj.util.tool.StringUtils;
import com.wsj.util.tool.Tool;
import com.wsj.web.subclass.displayBean.Magazine.MagazineClassExtendBean;
import com.wsj.web.vo.homeSite.MagazineClass;

public class MagazineClassDaoImpl extends HibernateDaoSupport implements IMagazineClassDao {

	public void add(MagazineClass magazineClass) throws DataAccessException {
		this.getHibernateTemplate().save(magazineClass);
	}

	public void delete(MagazineClass magazineClass) throws DataAccessException {
		this.getHibernateTemplate().delete(magazineClass);
	}

	public MagazineClass loadById(Integer id) throws DataAccessException {
		Object obj = null;
		MagazineClass magazineClass = new MagazineClass();
		obj = this.getHibernateTemplate().get(MagazineClass.class, id);
		if(obj!=null){
			magazineClass = (MagazineClass)obj;
		}
		return magazineClass;
	}

	@SuppressWarnings("unchecked")
	public List<MagazineClass> loadByNameId(Integer magazineNameId) throws DataAccessException {
		List<MagazineClass> list = new ArrayList<MagazineClass>();
		String sql = " from MagazineClass m where m.magazineName.id = ? ";
		list = this.getHibernateTemplate().find(sql,magazineNameId);
		return list;
	}
	
	public List loadTopByNameId(Integer magazineNameId, Integer top) throws DataAccessException {
		String sql = " from MagazineClass m where m.magazineName.id = ? ";
		List list = this.getSession().createQuery(sql).setInteger(0, magazineNameId).setMaxResults(top).list();
		if(StringUtils.isNotNull(list)){
			return list;
		}
		return null;
	}

	public void update(MagazineClass magazineClass) throws DataAccessException {
		this.getHibernateTemplate().saveOrUpdate(magazineClass);
	}

	public MagazineClass loadByNameAndNameId(String name, Integer nameId) throws DataAccessException {
		String sql = " from MagazineClass m where 1 = 1 and m.lanmuname = ? and m.magazineName.id = ?";
		List list = this.getHibernateTemplate().find(sql,new Object[]{name,nameId});
		MagazineClass magazineClass = null ;
		if(list!=null && list.size()>0){
			magazineClass = (MagazineClass)list.get(0);
		}
		return magazineClass;
	}
	
	
	/**
	 * 分页查询：
	 * 条件：直播名ID、栏目名、是否删除、是否推荐、开始时间、结束时间
	 * 返回：MagazineClass  列表集合
	 * */
	public PageResultSet loadPageList(String qkName, String lanmuname, Short shanchu, Short istj, String beginDate, String endDate, Integer page, Integer pageSize) throws DataAccessException {
		PageResultSet pageResultSet = new PageResultSet();
	    PerfectPageResultSet pageResult = new PerfectPageResultSet();
	    // 获取Session
	    Session session = SessionFactoryUtils.getSession(getSessionFactory(),true);

	    // 初始化SQL语句
	    StringBuffer stringBuffer = new StringBuffer(
	            " from MagazineClass as m  where 1=1 ");
	    
	    // 设置每页显示得记录数和开始页
	    pageResult.setPage(page, pageSize);

	    // 参数
	    List<Comparable> list = new ArrayList<Comparable>();
	    
	    // 期刊名
	    if(qkName!=null && !qkName.equals(""))
	    {
	    	qkName = "%"+qkName+"%";
	        stringBuffer.append(" and m.magazineName.qiname like ?");
	        list.add(qkName);
	    }
	    
	    // 栏目名
	    if(lanmuname!=null && !lanmuname.equals(""))
	    {
	    	lanmuname = "%"+lanmuname+"%";
	        stringBuffer.append(" and m.lanmuname like ?");
	        list.add(lanmuname);
	    }
	    
	    // 是否推荐 0 否 1 是
	    if(istj!=null&&!istj.equals((short)-1))
	    {
	    	stringBuffer.append(" and m.iftj = ?");
	        list.add(istj);
	    }
	    
	    // 是否删除 0 否 1 是
	    if(shanchu!=null&&!shanchu.equals((short)-1))
	    {
	    	stringBuffer.append(" and m.shanchu = ?");
	        list.add(shanchu);
	    }
	    
	    // 时间段
	    if(null!=beginDate && !"".equals(beginDate) && null!=endDate && !"".equals(endDate)){
	    	stringBuffer.append(" and m.inputdate >= '"+beginDate.trim()+" 00:00:00' and m.inputdate <= '"+endDate.trim()+" 23:59:59'");
	    }
	    
	    stringBuffer.append(" order by id desc ");

	    // 把集合转换成数组
	    String[] strParams = Tool.toArray(list);
	    
	    pageResultSet = pageResult.pageResultSet(stringBuffer.toString(),session, strParams);
	    
	    return pageResultSet;
	}

	
	/******
	 * 通过其刊名,获取期刊的栏目列表和下面所有的新闻列表
	 */
	public List<MagazineClassExtendBean> loadMagazineClassAndNewsDao(Integer magazineNameId) throws DataAccessException 
	{
		List ret=new ArrayList();
		List<MagazineClass> magazineClassList = this.getHibernateTemplate().find(" from MagazineClass mc where mc.shanchu = 0 and mc.magazineName.id = ?" ,magazineNameId);
		try {
			if(magazineClassList!=null  && !magazineClassList.isEmpty())
			{
				for(int j=0;j<magazineClassList.size();j++)
				{
					MagazineClass mc = (MagazineClass)magazineClassList.get(j);
					//通过分类id,获取下面搜索的期刊新闻
					List magazineList  = this.loadMagazineListByMagazineClassId(mc.getId());
					MagazineClassExtendBean magazineClassExtendBean  = new MagazineClassExtendBean(); 
					BeanUtils.copyProperties(magazineClassExtendBean,mc);
					magazineClassExtendBean.setMagazineList(this.loadMagazineListByMagazineClassId(mc.getId()));
					ret.add(magazineClassExtendBean);
				}
			}
		}
		catch (IllegalAccessException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return ret;
	}

	
	/*****
	 *  通过杂志分类id,返回杂志列表.
	 * @param id
	 * @return
	 */
	private List loadMagazineListByMagazineClassId(Integer id) 
	{
		//已经审核的
		String hql=" from Magazine as m where m.magazineClass.id = ? and m.sh =1 ";
		return  this.getHibernateTemplate().find(hql,id);
	}
	


}
